import 'dart:io';

import 'package:beng_beng_utils/utils/path/BengBengPath.dart';

import 'BBLogUtils.dart';

bool _appendStringToFile(String path, String content) {
  if (path.isEmpty || content.isEmpty) {
    return false;
  }
  path = path + "/${BBLogUtils.getInstance().appName}/log${getNameStr()}.txt";
  // print(path);
  try {
    final file = File(path);
    if (!file.existsSync()) {
      file.createSync(recursive: true);
    }
    // 检查文件写入权限
    if (!file.existsSync() || !file.statSync().modeString().contains('w')) {
      return false;
    }
    file.writeAsStringSync(content, mode: FileMode.append);
    return true;
  } catch (e) {
    return false;
  }
}

Future<bool> appendStringToFile(String content) async {
  return _appendStringToFile(
      (await getBengBengSavePublicPath())?.absolute.path ?? "", content);
}

Future<bool> clearAllLogFileByFilter({List<String>? filterList}) async {
  var directory = await getBengBengSavePublicPath();
  if (directory == null) {
    return false;
  }
  var path = directory.absolute.path + "/${BBLogUtils.getInstance().appName}/";
  try {
    final dir = Directory(path);

    if (dir.existsSync()) {
      final fileList = dir.listSync();

      for (final file in fileList) {
        if (file is File) {
          final filename = file.uri.pathSegments.last;

          // 检查文件名是否以"log"开头且以".txt"结尾
          if (filename.startsWith('log') && filename.endsWith('.txt')) {
            if (filterList == null || !filterList.contains(filename)) {
              // 如果不在filterList中，则删除文件
              await file.delete();
            }
          }
        }
      }
    }
    return true;
  } catch (e) {
    print("Error: $e");
    return false;
  }
}
